package model

import (
	"gorm.io/plugin/soft_delete"
	"reflect"
	"time"
)

type BaseModel struct {
	ID        uint `gorm:"primaryKey;size:16"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt *time.Time
	IsDel     soft_delete.DeletedAt `gorm:"softDelete:flag,DeletedAtField:DeletedAt" `
}

type ModelMap map[string]any

func (m *ModelMap) Set(key string, value any) {
	newValue := value
	switch value.(type) {
	case string:
		newValue = value.(string)
		if newValue == "" {
			return
		}
	case TaskStatus:
		newValue = value.(TaskStatus)
		if newValue == 0 {
			return
		}
	case *string:
		newValue = *value.(*string)
		if newValue == nil {
			return
		}
	case *TaskStatus:
		newValue = *value.(*TaskStatus)
		if newValue == nil {
			return
		}
	default:
		if value == nil {
			return
		}
	}
	(*m)[key] = newValue
}

func Struct2MapWithZero[T Task | User | BaseModel](s *T) ModelMap {
	t := reflect.TypeOf(*s)
	v := reflect.ValueOf(*s)
	m := make(ModelMap)
	for i := 0; i < t.NumField(); i++ {
		m[t.Field(i).Name] = v.Field(i).Interface()
	}
	return m
}

func Struct2MapWithoutZero[T Task | User | BaseModel](s *T) ModelMap {
	t := reflect.TypeOf(*s)
	v := reflect.ValueOf(*s)
	m := make(ModelMap)
	for i := 0; i < t.NumField(); i++ {
		m.Set(t.Field(i).Name, v.Field(i).Interface())
	}
	return m
}
